package com.nemodynamic.cattivial.facebook;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;


import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.actionbarsherlock.app.SherlockFragment;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.widget.LoginButton;
import com.nemodynamic.cattivial.R;
import com.nemodynamic.cattivial.utils.DLog;

public class FragmentFacebookLogInButton extends SherlockFragment {
	private static boolean isLogged = false;
	private UiLifecycleHelper uiHelper;
	private static final List<String> PERMISSIONS = Arrays.asList("publish_actions", "user_relationships");
	private static final List<String> READ_PERMISSION = Arrays.asList("basic_info", "user_relationships");
	private static final List<String> PUBBLISH_PERMISSION = Arrays.asList("publish_actions");
	private static final String TAG = "FragmentFacebookLogInButton";
	private OnLogInLogOutListener onLogInLogOutListener;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_login_button, container, false);
		LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
		authButton.setFragment(this);
		try {
			authButton.setReadPermissions(READ_PERMISSION);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return view;
	}

	public OnLogInLogOutListener getOnLogInLogOutListener() {
		return onLogInLogOutListener;
	}

	public void setOnLogInLogOutListener(OnLogInLogOutListener onLogInLogOutListener) {
		this.onLogInLogOutListener = onLogInLogOutListener;
	}

	private void onSessionStateChange(Session session, SessionState state, Exception exception) {
		if (state.isOpened()) {
			if (!isLogged) {
				isLogged = true;
				DLog.i(TAG, "Logged in...");
				if (onLogInLogOutListener != null)
					onLogInLogOutListener.onLogin();

			}
		} else if (state.isClosed()) {
			isLogged = false;
			DLog.i(TAG, "Logged out... : " + state + " Exception:" + exception);
			if (onLogInLogOutListener != null)
				onLogInLogOutListener.onLogout();
			try {
				PackageInfo info = getActivity().getPackageManager().getPackageInfo("it.genertel.fourtravelers", PackageManager.GET_SIGNATURES);
				for (Signature signature : info.signatures) {
					MessageDigest md = MessageDigest.getInstance("SHA");
					md.update(signature.toByteArray());
					Log.d("HASH KEY:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
					Log.d("SESSION APPID", Session.getActiveSession().getApplicationId());
					Log.d("STORED APPID", getString(R.string.facebook_app_id));
				}
			} catch (NameNotFoundException e) {

			} catch (NoSuchAlgorithmException e) {

			}
		}
	}

	private Session.StatusCallback callback = new Session.StatusCallback() {
		@Override
		public void call(Session session, SessionState state, Exception exception) {
			onSessionStateChange(session, state, exception);
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		uiHelper = new UiLifecycleHelper(getActivity(), callback);
		uiHelper.onCreate(savedInstanceState);
	}

	@Override
	public void onResume() {
		super.onResume();
		Session session = Session.getActiveSession();
		if (session != null && (session.isOpened() || session.isClosed())) {
			onSessionStateChange(session, session.getState(), null);
		}
		uiHelper.onResume();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Session session = Session.getActiveSession();
		if (session != null) {
			DLog.d(TAG, "" + session);
			session.onActivityResult(this.getActivity(), requestCode, resultCode, data);
			uiHelper.onActivityResult(requestCode, resultCode, data);
			// Check for publish permissions
			List<String> permissions = session.getPermissions();
			DLog.d(TAG, "" + permissions);
			if (!isSubsetOf(PERMISSIONS, permissions)) {
				Session.NewPermissionsRequest newPermissionsRequestPubblish = new Session.NewPermissionsRequest(this, PUBBLISH_PERMISSION);
				session.requestNewPublishPermissions(newPermissionsRequestPubblish);
				return;
			}
		}

	}

	private static boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
		for (String string : subset) {
			if (!superset.contains(string)) {
				return false;
			}
		}
		return true;
	}

	@Override
	public void onPause() {
		super.onPause();
		uiHelper.onPause();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		uiHelper.onDestroy();
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		uiHelper.onSaveInstanceState(outState);
	}

	public interface OnLogInLogOutListener {
		public void onLogin();

		public void onLogout();
	}
}
